﻿#region Copyright (c) 2006-2012 nHydrate.org, All Rights Reserved
// --------------------------------------------------------------------- *
//                           NHYDRATE.ORG                                *
//              Copyright (c) 2006-2012 All Rights reserved              *
//                                                                       *
//                                                                       *
// This file and its contents are protected by United States and         *
// International copyright laws.  Unauthorized reproduction and/or       *
// distribution of all or any portion of the code contained herein       *
// is strictly prohibited and will result in severe civil and criminal   *
// penalties.  Any violations of this copyright will be prosecuted       *
// to the fullest extent possible under law.                             *
//                                                                       *
// THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
// TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
// TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
// CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
// THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF THE NHYDRATE GROUP *
//                                                                       *
// UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
// PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
// SUBSTANTIALLY THE SAME, FUNCTIONALITY AS THIS PRODUCT                 *
//                                                                       *
// THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
// CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF NHYDRATE,          *
// THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO             *
// INSURE ITS CONFIDENTIALITY.                                           *
//                                                                       *
// THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
// PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
// EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
// THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
// SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                       *
// THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
// --------------------------------------------------------------------- *
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using nHydrate.Generator.Models;
using nHydrate.Dsl;

namespace nHydrate.DslPackage.Forms
{
	public partial class ImportColumns : Form
	{
		private Entity _entity = null;
		private List<Field> _fieldList = null;
		private Microsoft.VisualStudio.Modeling.Store _store = null;

		public ImportColumns()
		{
			InitializeComponent();

			lblText.Text = "Specify columns to import in the following format. All values are separated by a comma. The only required parameter is name.";
			lblHeader.Text = "Syntax:\r\nExample:";
			lblData.Text = "column_name[, data_type, length, allow_null]\r\n" +
				"first_name, varchar, 100, false\r\n" +
				"age, int,,true";
		}

		public ImportColumns(Entity entity, Microsoft.VisualStudio.Modeling.Store store)
			: this()
		{
			_store = store;
			_entity = entity;
			_fieldList = new List<Field>();
			_fieldList.AddRange(entity.Fields);
		}

		private void cmdOK_Click(object sender, EventArgs e)
		{
			var doClose = ProcessTable();
			if (doClose)
			{
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
		}

		private bool ProcessTable()
		{
			if (string.IsNullOrEmpty(txtText.Text.Trim()))
			{
				MessageBox.Show("There are no columns specified!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			using (var transaction = _store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
			{
				txtText.Text.Trim().Replace("\r\n", "\n");
				var lines = txtText.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
				var errors = new List<string>();
				var index = 1;
				foreach (var line in lines)
				{
					var arr = line.Split(',');
					if (arr.Length == 0)
					{
						errors.Add("There was an error on line " + index);
					}
					else
					{
						//Add column
						var field = new Field(_entity.Partition);
						field.Name = arr[0].Trim();
						_entity.Fields.Add(field);

						//Datatype
						if (arr.Length > 1 && !string.IsNullOrEmpty(arr[1]))
						{
							try
							{
								field.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), arr[1], true);
							}
							catch (Exception ex)
							{
								errors.Add("There was an error with the 'Datatype' on line " + index);
							}
						}

						//Length
						if (arr.Length > 2 && !string.IsNullOrEmpty(arr[2]))
						{
							int l;
							if (!int.TryParse(arr[2], out l))
							{
								errors.Add("There was an error with the 'Length' on line " + index);
							}
							else
							{
								field.Length = l;
							}
						}

						//AllowNull
						if (arr.Length > 3)
						{
							bool b;
							if (!bool.TryParse(arr[3], out b))
							{
								errors.Add("There was an error with 'Allow Null' on line " + index);
							}
							else
							{
								field.Nullable = b;
							}
						}

					}
					index++;
				}

				if (errors.Count > 0)
				{
					MessageBox.Show("There were errors.\r\n\r\n" + string.Join("\r\n", errors.ToArray()), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return false;
				}

				transaction.Commit();
			}

			return true;
		}

		private void cmdCancel_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}

	}
}
